package com.amose.springcloudoauth2server.config;

import com.amose.springcloudoauth2server.authentication.entity.Permission;
import com.amose.springcloudoauth2server.authentication.entity.UserInfo;
import com.amose.springcloudoauth2server.authentication.service.IPermissionService;
import com.amose.springcloudoauth2server.authentication.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yp
 * @date 2021/7/1
 * @since 1.0.0
 */
@Component
public class JdbcUserDetailsService implements UserDetailsService {

    @Autowired
    IUserInfoService userInfoService;

    @Autowired
    IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        UserInfo userInfo = userInfoService.queryByUserName(userName);
        if(userInfo == null){
            return null;
        }
        List<Permission> list = permissionService.queryPermissionListByUserId(userInfo.getId());
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        list.forEach(permission -> {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getPermission());
            grantedAuthorityList.add(grantedAuthority);
        });
        return new User(userInfo.getUserName(), userInfo.getPassword(),grantedAuthorityList);
    }
}
